<template>
    <!-- 新增 -->
    <el-dialog
    v-model="addBox"
    title="新增管理员的信息"
    width="550"
    destroy-on-close
    :close-on-click-modal="false"	
    :close-on-press-escape="false"
    draggable
    :center="true"
  >
    <div class="admin-info-add">
        <el-form
        :model="ruleFormAdd"
        :rules="rulesAdd"
        label-width="120px"
        ref="addFormRef"
        status-icon
    >
        <el-form-item label="设置用户名" prop="username">
            <el-input v-model="ruleFormAdd.username" placeholder="用户名长度保持在2到10位之间,中文,字母,数字任意组合" />
        </el-form-item>
        <el-form-item label="设置角色" prop="role" required>
            <el-select v-model="ruleFormAdd.role" placeholder="请选择角色" clearable>
                <el-option v-for="(item,index) in roleList.slice(1)"  :value="index" :key="index" :label="item" />
            </el-select>
        </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitNewAdmin()">
       提交
      </el-button>
    </el-form-item>
  </el-form>
    </div>
  </el-dialog>
    <!-- 编辑 -->
<el-dialog
    v-model="editBox"
    title="编辑管理员的信息"
    width="500"
    @closed="resetEditButton"
    destroy-on-close
    :close-on-click-modal="false"	
    :close-on-press-escape="false"
    draggable
    :center="true"
  >
    <div class="admin-info-editor">
        <div class="role-select" v-if="currentEdit.level !== 0">
                <label>设置角色</label>
                <el-select v-model="currentEdit.level" :disabled ="editor_btn_msg[0]==='编辑'" clearable>
                    <el-option v-for="(item,index)  in roleList.slice(1)" :value="index" :key="index" :label="item" />
                </el-select>
                <el-button type="primary" plain @click="handleEditorClick(editor_btn_msg[0]==='编辑',0)">{{editor_btn_msg[0]}}</el-button>
        </div>
        <div class="status-filter"  v-if="currentEdit.level !== 0">
            <label>设置状态</label>
                <el-radio-group v-model="currentEdit.status"  :disabled ="editor_btn_msg[1]==='编辑'" >
                    <el-radio :label="1">正常</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
                <el-button type="primary" plain @click="handleEditorClick(editor_btn_msg[1]==='编辑',1)">{{editor_btn_msg[1]}}</el-button>
        </div>
        <div class="password-change">
                <label>修改密码</label>
                <el-input v-model="currentEdit.pwd" type="password" show-password placeholder="请输入新密码" :disabled ="editor_btn_msg[2]==='编辑'"  />
                <el-button type="primary" plain @click="handleEditorClick(editor_btn_msg[2]==='编辑',2)">{{editor_btn_msg[2]}}</el-button>
        </div>
    </div>
  </el-dialog>
    <div class="admin-info-container">
        <!-- 顶部查询 -->
        <div class="top-query">
            <el-form  :model="formline" :inline="true" ref="searchForm" :rules="rules" status-icon class="query-form">
                <el-form-item label="检索" prop="username">
                    <el-input v-model="formline.username" placeholder="请输入账号" @keyup.enter="queryAdmin()"  clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="queryAdmin()" :icon="Search">查询</el-button>
                </el-form-item>
            </el-form>
           <div class="role-filter">
                <label>角色</label>
                <el-select
                    v-model="role"
                    placeholder="当前角色:全部"
                    clearable
                >
                    <el-option v-for="(item,index) in roleList" :key="index" :label="item" :value="index" />
                </el-select>
        </div>
          <div class="status-filter">
            <label>状态</label>
                <el-radio-group v-model="status">
                    <el-radio :label="-1">全部</el-radio>
                    <el-radio :label="1">正常</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
          </div>
          <div class="add-admin">
            <el-button type="warning" @click="openAddAdmin" :icon="Plus" circle />
          </div>
        </div>
        <el-divider />
        <!-- 管理员表格 -->
        <div class="admin-table-wrapper">
            <el-table
                class="admin-table"
                :data="tableData"
                :border="true"
                
            >
                <el-table-column prop="id" label="ID" width="120" :align="'center'" />
                <el-table-column prop="username" label="账号" min-width="200" :align="'center'" />
                <el-table-column prop="nickName" label="昵称" min-width="200" :align="'center'" />
                <el-table-column prop="role" label="角色" width="150" :align="'center'" >
                    <template #default="scope">  
                        <el-tag effect="dark">
                        {{ scope.row.role }}
                        </el-tag>
                    </template>  
                </el-table-column>
                <el-table-column prop="avatar" label="头像" width="100" :align="'center'" >
                    <template #default="scope">  
                        <el-avatar :size="60" :src="scope.row.avatar" />  
                    </template>  
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100" :align="'center'" >
                    <template #default="scope">  
                        <el-tag effect="dark" :type="scope.row.status==='正常'?'success':'danger'">
                        {{ scope.row.status }}
                        </el-tag>
                    </template>  
                </el-table-column>
                <el-table-column prop="creationTime" label="创建时间" sortable width="200" :align="'center'" />
                <el-table-column prop="opreate" label="操作" width="180" :align="'center'" >
                    <template #default="scope">
                        <el-button  size="small"  type="primary" :icon="Edit" @click="editAdminInfo(scope.row.id)" round>编辑</el-button>
                        <el-button  size="small" type="danger" v-if="scope.row.role !== '超级管理员'" :icon="Delete" @click="isDeleteAdmin(scope.row.id)" round>删除</el-button>
                    </template>  
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页部分 -->
        <div class="pagination">
            <el-pagination
                v-model:current-page="currentPage"
                :page-size="pageSize"
                :page-count="parseInt(total%pageSize === 0?total/pageSize:total/pageSize+1)"
                :background="background"
                layout="total, prev, pager, next, jumper"
                :total="total"
                >
            </el-pagination>   
        </div>
    </div>

</template>

<script setup>
    import { ref,onBeforeMount,watch} from 'vue';
    // import Icon from '@/components/Icon.vue';
    import {getAdmin, editAdmin,addAdmin,deleteAdmin,findAdmins,getAdminFilter } from '@/api/index.js';
    // import {usePageStore} from '@/store/modules/page.js';
    import {Delete,Edit,Search,Plus} from '@element-plus/icons-vue'
    import { ElMessage,ElDivider, ElMessageBox,ElForm, ElFormItem, ElButton,ElInput,ElSelect,ElRadioGroup,ElPagination,ElTableColumn,ElTag,ElTable,ElAvatar,ElDialog,ElRadio,ElOption } from 'element-plus'
    /*模板引用变量*/
    const searchForm = ref(null);
    const addFormRef = ref(null);
    /* 校验--顶部筛选 */
    const formline  = ref({username:''});
    const rules = {
        username: [
            { required: true, message: '请输入账号', trigger: 'blur' },
            {type:'string',pattern:/^[a-zA-Z0-9\u4e00-\u9fa5]{1,10}$/,trigger:'change',message:"账号格式错误"}
        ],
    };
    /* 校验--新增管理员 */
    const ruleFormAdd = ref({username:'',role:''});
    const rulesAdd = {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' },{type:'string',pattern:/^[a-zA-Z0-9\u4e00-\u9fa5]{2,10}$/,trigger:'change',message:"用户名长度2到10位,字母,数字,汉字任意组合"}],
        role: [{ required: true, message: '请选择角色', trigger: 'blur' }],
    };
    /* 表格部分变量 */
    const role  = ref(0);
    const status  = ref(-1);
    const tableData  = ref([]);
    onBeforeMount(()=>{//limit,order,orderBy,offset
        getAdminInfo(5,'asc','level',0);
    })
    //角色列表
    const roleList = [
        '全部',
        '超级管理员',
        '管理员',
        '维护员',
        '审核员',
    ];
/*分页部分变量*/
    const currentPage = ref(1);
    const pageSize = ref(5);
    const background = ref(true);//是否显示背景色
    const total = ref(null);
    watch(currentPage,(newVal)=>{
        let offset = (newVal-1)*pageSize.value;
        getAdminInfo(5,'asc','level',offset);
    })
    watch(status,()=>{
        filterAdmin();
    })
    watch(role,()=>{
      filterAdmin();  
    })
/*操作部分变量*/
    const editBox = ref(false);//编辑框默认关闭
    const addBox = ref(false);//添加框默认关闭
    let currentEdit = ref({//当前编辑框的数据
        id:0,
        level:null,
        status:null,
        pwd:'',
    });//当前编辑的数据
    const password = ref('');//密码
    let editor_btn_msg = ref(['编辑','编辑','编辑']);
/*方法*/
//获取管理员信息
const getAdminInfo = (limit,order,orderBy,offset)=>{
    //orderBy level asc limit 5 offset 0
    getAdmin({limit,order,orderBy,offset}).then(res=>{
        if(res.status.code === 200){
            tableData.value = res.data.info;
            total.value = res.data.total;
        }else{
            ElMessage.error(res.status.msg);
        }
    })
}
   //查询按钮单击事件
   const queryAdmin = ()=>{
    searchForm.value.validate((valid)=>{
           if(valid){
            findAdmins({name:formline.value.username,limit:pageSize.value,offset:0}).then(res=>{
                if(res.status.code === 200){
                    tableData.value = res.data.info;
                    total.value = res.data.total;
                }else{
                    tableData.value = [];
                    total.value = 0;
                    ElMessage.error(res.status.msg);
                }
            })
           }else{
               ElMessage.error('请输入账号');
           }
       })
   }
   //筛选角色
   const filterAdmin = ()=>{
       getAdminFilter({role:role.value,status:status.value,limit:pageSize.value,offset:(currentPage.value-1)*pageSize.value}).then(res=>{
           if(res.status.code === 200){
               tableData.value = res.data.info;
               total.value = res.data.total;
           }else{
               ElMessage.error(res.status.msg);
           }
       })
   }
   //打开新增管理员框
   const openAddAdmin = ()=>{
       addBox.value = true;
   }
   //打开编辑框
   const editAdminInfo = (id)=>{
        //获取当前用户操作的id
        editBox.value = true;
        currentEdit.value.id = id;
        //根据id拿到被操作的用户信息
        let adminItem = tableData.value.find(item => item.id === id);
        currentEdit.value.level = roleList.slice(1).indexOf(adminItem.role);
        currentEdit.value.status = adminItem.status === '正常'?1:0;
   }
//删除管理员
const isDeleteAdmin = (id)=>{
    //询问用户是否删除
    ElMessageBox.confirm(
    '确定永久性删除ID为 '+id+' 的管理员吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal:false,
      closeOnPressEscape:false,	
      draggable:true,
      showClose:false,
      type: 'warning',
      center: true,
    }
  )
    .then(() => {
      //向后端发起删除请求
      IdentifyAdmin('delete',id);
    })
    .catch(() => {

    })
}
//处理编辑框按钮操作
const handleEditorClick = (isRelease,index)=>{
    //打开按钮
    if(isRelease){
        editor_btn_msg.value[index] = '提交';
    }else{
        IdentifyAdmin('edit',index);
    }
}
//重置按钮
const resetEditButton = ()=>{
    editor_btn_msg.value.fill('编辑');
}
//提交的新用户的信息  -- 后端先核对密码，再做处理
const submitNewAdmin = ()=>{
    addFormRef.value.validate((valid)=>{
        if(valid){
            //调用核验方法
            IdentifyAdmin('add',null);
        }
    })
}
//核验方法
const IdentifyAdmin = (type,i)=>{
 //要求超级管理员进行密码核验
 ElMessageBox.prompt('请输入您账户的密码', '身份核实', {
    confirmButtonText: '确定',
    inputType: 'password',
    showCancelButton:false,
    draggable:true,
    closeOnClickModal:false,
    closeOnPressEscape:false,
    center:true,
    inputPattern:/^[^\s]+$/,
    inputErrorMessage: '密码不为空',
    }).then(({ value }) => {
        if(type === 'add'){//true为新增管理员,false为编辑管理员
           addAdminInfo(value);
        }else if(type === 'edit'){
            updateAdminInfo(value,i);
        }else{
            deleteAdminInfo(i,value);
        }
    }).catch(() => {})
}
//删除管理员
const deleteAdminInfo = (id,password)=>{
    deleteAdmin({id,password}).then((res)=>{
        if(res.status.code === 200){
            ElMessage({message:res.status.msg,type:'success'});
            //重新获取管理员列表
            let offset = (currentPage.value-1)*pageSize.value;
            getAdminInfo(5,'asc','level',offset);
        }else{
            ElMessage({message:res.status.msg,type:'error'});
        }
    })
}
//更新管理员信息
const updateAdminInfo = (pass,index)=>{
    let field = '';
    if(index === 0){
        field = 'level';
    }else if(index === 1){
        field = 'status';
    }else{
        field = 'pwd';
    }
    let value = currentEdit.value[field];
    let params = {field,newValue:value,password:pass,id:currentEdit.value.id};
    editAdmin(params).then((res)=>{
        if(res.status.code === 200){//修改成功后,按钮重新回到编辑状态
            editor_btn_msg.value[index] = '编辑';
            if(field === 'level'){
                let arr = roleList.slice(1);
                value = arr[value];
                field = 'role';
            }else if(field === 'status'){
                value = value === 1 ? '正常' : '禁用';
            }
            let targetIndex = tableData.value.findIndex(item=>item.id === currentEdit.value.id);
            tableData.value[targetIndex][field] = value;
            editBox.value = false;
            ElMessage.success(res.status.msg);
        }else{
            ElMessage.error(res.status.msg);
        }
    })
}
const addAdminInfo = (pass)=>{
    //向后端发起新增管理员信息的请求
    let params = {...ruleFormAdd.value,password:pass};
    addAdmin(params).then((res)=>{
        //修改成功后,新增窗口关闭,弹出新用户的密码
        if(res.status.code === 200){
            addBox.value = false;
            countDownBox(res);
            //新增管理员后,重新获取管理员列表
            tableData.value.push(res.data);
            ruleFormAdd.value = {username:'',role:''};
        }else{
            ElMessage.error(res.status.msg);
        }
    })
}
//密码倒计时确认框
const countDownBox = (res)=>{
const lock = ref(true);
const countDownText = ref('确定(10秒)');
let timer;
let count = 10;
  timer = setInterval(() => {
      count--;
      countDownText.value = `确定(${count})秒`;
  }, 1000);
  setTimeout(() => {
    clearInterval(timer);
    countDownText.value = '确定';
  },10000);
  // 显示alert框
  ElMessageBox.alert(
    `<p><Strong style='color:darkred'>请牢记您的用户密码,密码仅显示一次</Strong></p>`,res.data.password,
    {
      confirmButtonText: countDownText,
      showCancelButton: false,
      closeOnClickModal: false,
      showClose:false,
      closeOnPressEscape:false,	
      dangerouslyUseHTMLString: true,
      center: true,
      customClass: {
        confirmButton: lock.value ? 'el-button--disabled' : '',
      },
    },
  );
}
</script>

<style scoped lang='scss'>

@mixin flexBetween{
    display: flex;
    justify-content: space-between;
}
.admin-table-wrapper{
    display: flex;
    flex-direction: column;
    justify-content:flex-start;
    height: 100%;
}
.admin-info-container{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
}
.admin-info-editor{
    label{
        width:100px;
    }
    .role-select,.status-filter,.password-change{
        @include flexBetween;
        margin-top: 10px;
    }
}
label{
    display: inline-block;
    width: 50px;
    font-size: 14px;
    line-height: 30px;
    color: #606266;
}
.top-query{
    display: flex;
    width:100%;
    height:50px;
    margin-top:20px;
    justify-content: space-around;
    .role-filter{
       display: flex;
       margin-right:30px;
    }
    .status-filter{
        display: flex;
        :deep(.el-radio-group){
            display: block !important;
        }
    }
}
:deep(.el-select__wrapper){
    min-width:180px;
}  
.admin-avatar{
    display: inline-block;
    width:80px;
    height: 80px;
    border-radius: 50%;
}
.admin-table{
    width:99% !important;
    margin: 0 auto;
    height: 65vh;
}
.pagination{
    margin:5px;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>